import FormPdfHtml from "@/views/modules/common/FormPdfHtml.vue";
import {Util} from "@lowcode/jpaas-base-lib";
import FormWordTemplateApi from "@/common/api/form/formWordTemplate.js";
import {PdfDialog,PrintQrCode} from "@lowcode/jpaas-share-component";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
/**
 * pdf公共处理方法
 */

export default {
    data() {
        return {
        }
    },
    methods: {
        pdfI18(name,text,key){
            return this.$ti18(name,text,"formBaseApi",key);
        },
        /**
         * pdf打印
         * @param btn
         */
        pdfPrint(btn) {
            let formBuild=this.getFormVm();
            let dataJson = formBuild.getData() || formBuild.formData;
            //打开pdf模板
            let self = this;
            let name=this.$i18(btn.i18nJson,"标题");
            let conf = {
                component: FormPdfHtml,
                title: name ,
                widthHeight: [`100%`, `100%`]
            }
            let btnConfig=btn.config;
            let baseConf = {
                curVm: self,
                data: {   //传递参数
                    pkId: btnConfig.defId,
                    dataJson: dataJson,
                    formConfig:formBuild.formConfig
                }
            }
            let config = Object.assign(baseConf, conf)
            Util.open(config, function (action) {
            })
        },
        /**
         * 下载PDF
         * @param btn
         */
        pdfDownload(btn) {
            let formBuild=this.getFormVm();
            btn.loading = true;
            var self = this;
            var formData=formBuild.getData();
            var boDefId= btn.config.boDefId;
            var formName=formBuild.name;
            var templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: self.$ti18('rxMsa.actionTips','操作提示'), description:this.pdfI18('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }
            this.$confirm({
                content: this.pdfI18('msa.pdfDownConfirm','您确定要下载PDF文档吗?'),
                zIndex: 40000,
                okText: self.$ti18('rxForm.ackBtn','确认'),
                cancelText: self.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    //打印当前word 表单别名与表单数据
                    FormWordTemplateApi.pdfPrint({boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId}).then(res=>{
                        if(!res){
                            self.$notification['error']({
                                message: self.$ti18('rxMsa.actionTips','操作提示'),
                                description:this.pdfI18('msa.pdfDownError','生成PDF失败!'),
                            });
                            btn.loading = false;
                            return;
                        }
                        let blob = new Blob([res], {
                            type: 'application/pdf'
                        });
                        let fileName = formName + '.pdf';
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob, fileName);
                        } else {
                            var link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = fileName;
                            link.click();
                            //释放内存
                            window.URL.revokeObjectURL(link.href)
                        }
                        btn.loading = false;
                    });
                },
                onCancel() {
                    btn.loading = false;
                }
            });
        },
        /**
         * 打开PDF
         * @param btn
         */
        openPdf(btn) {
            let formBuild=this.getFormVm();
            let self = this;
            let formData=formBuild.getData();
            let boDefId= btn.config.boDefId;
            let templateId=btn.config.templateId;
            if(!btn.config.templateId){
                self.$notification['warning']({message: self.$ti18('rxMsa.actionTips','操作提示'), description:this.pdfI18('msa.wordPrintTips','未绑定word模板!'),});
                return;
            }
            let params={boDefId:boDefId,formData:JSON.stringify(formData),single:true,templateId:templateId};
            Util.open( {
                component: PdfDialog,
                curVm: this,
                max: true,
                title: this.pdfI18('openPdf','打开PDF'),
                data:{
                    params:params
                }
            })
        },
        printPdf(btn){
            btn.loading=true;
            this.$message.warning(this.pdfI18('msa.printPdfTips','打印启动中...'));
            this.timeOut = setTimeout(()=>{
                this.printPdfImg(btn)
            },300)
        },
        printPdfImg(btn){
            let scale = 1;
            let self_=this;
            let dmoWidth = document.querySelector(".previewBox").offsetWidth;
            if(dmoWidth>595.28){
                scale = dmoWidth / 595.28 ;
            }
            html2Canvas(document.querySelector(".previewBox"), {
                allowTaint: true, // 开启跨域
                scale // 提升画面质量，但是会增加文件大小
            }).then(function(canvas) {
                const contentWidth = canvas.width / scale;
                const contentHeight = canvas.height / scale;
                let pageHeight = contentWidth / 592.28 * 841.89 ;  // 1762.58 canvas上每一页的高度
                //未生成pdf的html页面高度
                let leftHeight = contentHeight;
                var position = 0;
                var imgWidth = 595.28; // A4 宽度
                var imgHeight = 592.28/ contentWidth * contentHeight; // A4总高度
                const PDF = new JsPDF('', 'pt', 'a4');
                const pageData = canvas.toDataURL('image/jpeg', 1.0);
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
                } else {
                    while(leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight ;
                        position =(position + 10 ) - 841.89;
                        //避免添加空白页
                        if(leftHeight > 0) {
                            PDF.addPage();
                        }
                    }
                }
                //  PDF.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
                let url=PDF.output("bloburl");
                btn.loading=false;
                Util.open({
                    component: PrintQrCode,
                    curVm: self_,
                    max: true,
                    title: self_.pdfI18('printPdf','打印PDF'),
                    data: {url: url}
                }, function (action) {
                });
            })
        },
    }
}
